<script setup>
import {reactive} from 'vue';
import {useRouter} from "vue-router";

const router = useRouter();
let item = reactive({
  name: '',
  sps: []
})

const pageData = reactive({
  inputSp: '',
  selectSpNameIndex: -1
})

const addSp = () => {
  if (pageData.inputSp === '') {
    return
  }
  if (pageData.selectSpNameIndex === -1) {
    addSpName()
  } else {
    addSpItem(pageData.selectSpNameIndex)
  }
}
const addSpName = () => {
  item.sps.push({
    spName: pageData.inputSp,
    spItems: []
  })
  pageData.inputSp = ''
}
const addSpItem = (index) => {
  item.sps[index].spItems.push(pageData.inputSp)
  pageData.inputSp = ''
}
const onSelectSpName = (index) => {
  if (pageData.inputSp === item.sps[index].spName) {
    pageData.selectSpNameIndex = -1;
  } else {
    pageData.selectSpNameIndex = index
  }
}
const onSubmit = () => {
  fetch(`${process.env.VUE_APP_API}/items`, {
    method: 'POST',
    headers: new Headers({
      'Content-Type': 'application/json'
    }),
    body: JSON.stringify(item)
  }).then((res) => {
    console.log(res)
    if (res.ok) {
      router.push('/item-list')
    }
  })
}
</script>

<template>
<a-form>
  <a-form-item label="商品名称">
    <a-input v-model:value="item.name"></a-input>
  </a-form-item>
  <a-form-item label="商品规格">
    <template v-for="(sp,index) in item.sps" :key="index">
      <a-checkable-tag :checked="index === pageData.selectSpNameIndex" @change="onSelectSpName(index)">
        {{sp.spName}}
      </a-checkable-tag>
      <a-tag v-for="(spItem,index) in sp.spItems" :key="index">
        {{spItem}}
      </a-tag>
      <br/>
    </template>
    <a-input v-model:value="pageData.inputSp"
             :placeholder="pageData.selectSpNameIndex !== -1 ? `请输入${item.sps[pageData.selectSpNameIndex].spName}的规格项` : '请输入规格'"></a-input>
    <a-button type="primary" @click="addSp()">添加</a-button>
  </a-form-item>
  <a-form-item>
    <a-button type="primary" @click="onSubmit">完成</a-button>
  </a-form-item>
</a-form>
</template>